# 创建一个链表

"""
在Python中创建一个链表通常意味着定义一个节点类（Node）和一个链表类（LinkedList）。下面是一个简单的单向链表的实现
"""


class Node:
    def __init__(self, data):
        self.data = data  # 节点存储的数据
        self.next = None  # 指向下一个节点的指针


class LinkedList:
    def __init__(self):
        self.head = None  # 链表的头部节点

    def append(self, data):
        """在链表末尾添加一个新节点"""
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def prepend(self, data):
        """在链表头部添加一个新节点"""
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def delete_by_value(self, data):
        """根据节点的值删除节点"""
        current = self.head
        if current and current.data == data:
            self.head = current.next
            return
        prev = None
        while current and current.data != data:
            prev = current
            current = current.next
        if current is None:
            return
        prev.next = current.next

    def print_list(self):
        """打印链表中的所有元素"""
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")


# 使用LinkedList类
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.prepend(0)
ll.print_list()  # 应该打印: 0 -> 1 -> 2 -> 3 -> None
ll.delete_by_value(2)
ll.print_list()  # 应该打印: 0 -> 1 -> 3 -> None
